﻿using Common.Models;
using Core.Entities.EC;
using Infrastructure.Services;
using Infrastructure.Services.EC;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace WebZHX.Controllers.EC
{
    /// <summary>
    /// 能源信息控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class EnergyController : BaseController<Energy, string>
    {
        private readonly EnergyService _energyService;

        public EnergyController(
            BaseService<Energy, string> service,
            EnergyService energyService)
            : base(service)
        {
            _energyService = energyService;
        }

        /// <summary>
        /// 根据设备名称查询能源信息
        /// </summary>
        /// <param name="devName">设备名称</param>
        /// <returns>能源信息列表</returns>
        [HttpGet("device/{devName}")]
        public async Task<ActionResult<IEnumerable<Energy>>> GetByDevName(string devName)
        {
            var result = await _energyService.GetByDevNameAsync(devName);
            return Ok(result);
        }

        /// <summary>
        /// 根据工厂名称查询能源信息
        /// </summary>
        /// <param name="factoryName">工厂名称</param>
        /// <returns>能源信息列表</returns>
        [HttpGet("factory/{factoryName}")]
        public async Task<ActionResult<IEnumerable<Energy>>> GetByFactoryName(string factoryName)
        {
            var result = await _energyService.GetByFactoryNameAsync(factoryName);
            return Ok(result);
        }

        /// <summary>
        /// 根据车间名称查询能源信息
        /// </summary>
        /// <param name="workshop">车间名称</param>
        /// <returns>能源信息列表</returns>
        [HttpGet("workshop/{workshop}")]
        public async Task<ActionResult<IEnumerable<Energy>>> GetByWorkshop(string workshop)
        {
            var result = await _energyService.GetByWorkshopAsync(workshop);
            return Ok(result);
        }

        /// <summary>
        /// 根据物质类型查询能源信息
        /// </summary>
        /// <param name="substance">物质类型</param>
        /// <returns>能源信息列表</returns>
        [HttpGet("substance/{substance}")]
        public async Task<ActionResult<IEnumerable<Energy>>> GetBySubstance(string substance)
        {
            var result = await _energyService.GetBySubstanceAsync(substance);
            return Ok(result);
        }

        /// <summary>
        /// 根据时间段查询能源信息
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>能源信息列表</returns>
        [HttpGet("time-range")]
        public async Task<ActionResult<IEnumerable<Energy>>> GetByTimeRange(
            [FromQuery] DateTime startTime,
            [FromQuery] DateTime endTime)
        {
            var result = await _energyService.GetByTimeRangeAsync(startTime, endTime);
            return Ok(result);
        }

        /// <summary>
        /// 高级分页查询能源信息
        /// </summary>
        /// <param name="dto">查询参数</param>
        /// <returns>分页结果</returns>
        [HttpPost("advanced-query")]
        public async Task<ActionResult<PagedResult<Energy>>> AdvancedPagedQuery([FromBody] EnergyService.EnergyQueryDto dto)
        {
            var result = await _energyService.AdvancedPagedQueryAsync(dto.Filter, dto.Energy);
            return Ok(result);
        }

        /// <summary>
        /// 获取指定物质的能耗统计
        /// </summary>
        /// <param name="substance">物质类型</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>总能耗量</returns>
        [HttpGet("statistics/total-consumption")]
        public async Task<ActionResult<decimal>> GetTotalEnergyConsumption(
            [FromQuery] string substance,
            [FromQuery] DateTime startTime,
            [FromQuery] DateTime endTime)
        {
            var result = await _energyService.GetTotalEnergyConsumptionAsync(substance, startTime, endTime);
            return Ok(result);
        }

        /// <summary>
        /// 保存能源信息
        /// </summary>
        /// <param name="model">能源信息</param>
        /// <returns>操作结果</returns>
        [HttpPost("save")]
        public async Task<ActionResult<Energy>> SaveEnergy([FromBody] Energy model)
        {
            // 验证必填字段
            if (string.IsNullOrEmpty(model.DevName))
            {
                return BadRequest("设备名称不能为空");
            }

            if (string.IsNullOrEmpty(model.Substance))
            {
                return BadRequest("物质类型不能为空");
            }

            if (model.EnergyConsumption <= 0)
            {
                return BadRequest("能耗量必须大于0");
            }

            try
            {
                if (string.IsNullOrEmpty(model.Id))
                {
                    // 新增
                    model.Id = Guid.NewGuid().ToString();

                    if (!model.CreateTime.HasValue)
                    {
                        model.CreateTime = DateTime.Now;
                    }

                    var result = await _energyService.CreateAsync(model);
                    return CreatedAtAction(nameof(Get), new { id = result.Id }, result);
                }
                else
                {
                    // 修改
                    var existingRecord = await _energyService.GetByIdAsync(model.Id);
                    if (existingRecord == null)
                    {
                        return NotFound($"ID为{model.Id}的记录不存在");
                    }

                    var result = await _energyService.UpdateAsync(model);
                    return Ok(result);
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"保存失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 批量导入能源数据
        /// </summary>
        /// <param name="models">能源数据列表</param>
        /// <returns>操作结果</returns>
        [HttpPost("batch-import")]
        public async Task<ActionResult> BatchImport([FromBody] IEnumerable<Energy> models)
        {
            try
            {
                await _energyService.BatchImportAsync(models);
                return Ok("批量导入成功");
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"批量导入失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取所有的物质类型
        /// </summary>
        /// <returns>物质类型列表</returns>
        [HttpGet("substances/all")]
        public async Task<ActionResult<IEnumerable<string>>> GetAllSubstances()
        {
            var allRecords = await _energyService.GetAllAsync();
            var substances = allRecords.Select(e => e.Substance).Distinct().ToList();
            return Ok(substances);
        }

        /// <summary>
        /// 获取所有的设备名称
        /// </summary>
        /// <returns>设备名称列表</returns>
        [HttpGet("devices/all")]
        public async Task<ActionResult<IEnumerable<string>>> GetAllDevices()
        {
            var allRecords = await _energyService.GetAllAsync();
            var devices = allRecords.Select(e => e.DevName).Distinct().ToList();
            return Ok(devices);
        }
        /// <summary>
        /// 能耗时间查询报表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("EC/ReportPage")]
        public async Task<ActionResult<Energy>> ReportTimeQuery( EnergyService.EnergyQueryDto dto)
        {
            //时间处理
            if (!string.IsNullOrEmpty(dto.Energy.TimeCondition))
            {
                if (dto.Energy.TimeType == "year")
                {
                    dto.Energy.TimeCondition = dto.Energy.TimeCondition + '至' + Convert.ToDateTime(dto.Energy.TimeCondition).AddYears(1);
                }
                if (dto.Energy.TimeType == "month")
                {
                    dto.Energy.TimeCondition = dto.Energy.TimeCondition + '至' + Convert.ToDateTime(dto.Energy.TimeCondition).AddMonths(1);
                }
                if (dto.Energy.TimeType == "date")
                {
                    dto.Energy.TimeCondition = dto.Energy.TimeCondition + '至' + Convert.ToDateTime(dto.Energy.TimeCondition).AddDays(1);
                }
            }
            
            var result = await _energyService.AdvancedPagedQueryAsync(dto.Filter, dto.Energy);
            return Ok(result);
        }
        #region 设备看板信息

        /// <summary>
        /// 排名信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("EC/KANBAN_PM")]
        public async Task<ActionResult<object>> KanB_PM()
        {
           return await _energyService.PaiMing();
        }

        #endregion
    }
}